' Triennial Review Validation Script
Option Strict Off
imports System
imports Humans=PHSRAG.Insight21.Humans
imports PHSRAG.Insight21.BusinessObjects
imports FormsManagement = PHSRAG.Insight21.FormsManagement
imports System.Collections
imports Utility=PHSRAG.Utility

module Script
    sub Main()

        ' Pages for rediction
        const overviewPageRedirection = -2
		const AttachmentsPageRedirection = -1

		dim attachmentsLogItemAdded as boolean = false

        intrinsicProtocol.BiologicalAgent = false
        intrinsicProtocol.ToxicChem = false
        intrinsicProtocol.RadioIsotope = false
		
        For Each questionnaireAnswer As FormsManagement.QuestionnaireAnswer In intrinsicProtocolVersion.QuestionnaireAnswers

            ' Create a validation error if there is a QA with a default name (for multiples) 
            ' --> We do this so that "Move to Rex" doesn't fail when trying to move over blank forms
            ' --> Note that we don't handle Sponsors b/c we only move over the primary sponsor to REX so blank
            ' forms are okay and won't fail the "Move to Rex"
            if (questionnaireAnswer.Name = FormsManagement.Constants.AnimalsQuestionnaireAnswerDefaultNames.Hazardous)
                Dim category as string = "Hazardous Agent Administration and Use"
                Dim description as string = "You have indicated that the study will include a hazardous material.  Please either complete the form or remove it from the study."
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy, intrinsicProtocolProcess.Id, overviewPageRedirection, overviewPageRedirection, category, category, "", "", description, false)
                SaveLogItem(logItem)	
            end if

            Dim qV as FormsManagement.QuestionnaireVersion = questionnaireAnswer.QuestionnaireVersion

            'The following for loop checks the availability of the required documents
            For Each qD As FormsManagement.QuestionDocument In qV.documents
                If (qD.Type <> Nothing) Then
                    If (qD.IsRequired) Then

                        'Get the type of the question. If the question's type is MultiInput or DropDownMultiSelect, then for each entry, need a enforce a document
                        dim isMultiInputOrMultiSelect as boolean = false
                        for each item as FormsManagement.QuestionnaireItem in qV.Items
                            if (item.Name = qD.ItemName) then
                                if (item.Type = FormsManagement.QuestionnaireItem.MultiSelectItemType or item.Type = FormsManagement.QuestionnaireItem.DropDownMultiSelectItemType) then
                                    isMultiInputOrMultiSelect = true
                                end if
                                exit for
                            end if
                        next

                        if (not isMultiInputOrMultiSelect) then
                            'If the document to be attached is required
                            For each answer as FormsManagement.Answer in questionnaireAnswer.GetAnswers(qD.ItemName)
                                if (answer.value = qD.ItemValue) then
                                    Dim attached As Boolean = False
                                    'Get the attached documents from the protocol document.
                                    For Each pD As Humans.ProtocolDocument In intrinsicProtocolProcess.ProtocolDocuments
                                        'If the user has opted to send the hard copy of the document,No Log Item should be logged.
                                        If ((qD.Type = pD.Type) and (pD.IsHardCopy or pD.DocumentId >0)) Then
                                            attached = True
                                            Exit For 'exit Hardcopy Check
                                        End if  
                                    Next 
                                    If attached = False Then
                                        Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
                                        logItem.QuestionnaireVersionId=-1'qV.Id(assigned to -1, just to redirect the user to the attachments page)
                                        logItem.QuestionnaireAnswerId=-1'questionnaireAnswer.Id(assigned to -1, just to redirect the user to the attachments page)
                                        logItem.Type = "Attachments"'qD.Type(qD.Type returned a refcode,hence hardcoded )
                                        logItem.Category = "Attachments"
                                        logItem.QuestionName = qD.ItemName
                                        logItem.Answer = qD.ItemValue
                                        logItem.Description = qD.ValidationMessage
                                        logItem.Completed =False
                                        SaveLogItem(logItem)
                                        attachmentsLogItemAdded = true
                                    End If
                                    exit for
                                end if
                            Next
                        else 
                            Dim count as integer = 0
                            Dim answersList as new ArrayList()
                            answersList = questionnaireAnswer.GetAnswers(qD.ItemName)
                            'Get the attached documents from the protocol document.
                            For Each pD As Humans.ProtocolDocument In intrinsicProtocolProcess.ProtocolDocuments
                                'If the user has opted to send the hard copy of the document,No Log Item should be logged.
                                If ((qD.Type = pD.Type) and (pD.IsHardCopy or pD.DocumentId >0)) Then
                                    count = count + 1
                                End if  
                            Next 
                            If count < answersList.Count  Then
                                Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
                                logItem.QuestionnaireVersionId=-1'qV.Id(assigned to -1, just to redirect the user to the attachments page)
                                logItem.QuestionnaireAnswerId=-1'questionnaireAnswer.Id(assigned to -1, just to redirect the user to the attachments page)
                                logItem.Type = "Attachments"'qD.Type(qD.Type returned a refcode,hence hardcoded )
                                logItem.Category = "Attachments"
                                logItem.QuestionName = qD.ItemName
                                logItem.Answer = qD.ItemValue
                                logItem.Description = qD.ValidationMessage
                                logItem.Completed =False
                                SaveLogItem(logItem)
                                attachmentsLogItemAdded = true
                            End If

                        end if

                    End If
                End If

            Next

            if questionnaireAnswer.QuestionnaireVersion.Questionnaire.Name = "Hazardous Agent Administration and Use"
                Dim hazardType as string = questionnaireAnswer.GetAnswerValue("HazardType")
                select case hazardType
                    case "Bio"
                        intrinsicProtocol.BiologicalAgent = true
                    case "Chem"
                        intrinsicProtocol.ToxicChem = true
                    case "Rad"
                        intrinsicProtocol.RadioIsotope = true
                end select
            end if
        next

		'verify if all the ProtocolDocument records are either marked as hardcopy or there is an attachment tied to it
		If not attachmentsLogItemAdded then
			For Each pD As Humans.ProtocolDocument In intrinsicProtocolProcess.ProtocolDocuments
				If not (pD.IsHardCopy or pD.DocumentId >0) Then
					LogMissingItem(AttachmentsPageRedirection, AttachmentsPageRedirection, _
							"Attachments", string.empty, string.empty, string.empty, "Attachment missing for " + pD.Name)
				End if  
			Next
		End If

        Dim studyStaffCollection As Humans.StudyStaff = new Humans.StudyStaff(intrinsicCachePolicy)
        studyStaffCollection.Load(intrinsicConnection,intrinsicProtocolProcess.protocolId,intrinsicProtocolProcess.Id)
        Dim studyStaff as ArrayList = studyStaffCollection.GetStudyStaffList()

        ' Check that each staffPerson has a role
        For Each person as Humans.StaffPerson in studyStaff
            if person.Role.trim() = "Principal Investigator" and person.InstitutionalName <> "MGH" then
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
                logItem.QuestionnaireVersionId=0'qV.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
                logItem.QuestionnaireAnswerId=0'questionnaireAnswer.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
                logItem.Type ="Staff & Access"
                logItem.Category ="Staff & Access"
                logItem.QuestionName = "PI's organization"
                logItem.Answer =""
                logItem.Description ="The Principal Investigator for a study must belong to MGH." 'qI.ValidationMessage(There exists no validationMessage for this qI,so the Description is hardCoded)
                logItem.Completed =False
                SaveLogItem(logItem)				
            else if person.Role.trim()="" then
                Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
                logItem.QuestionnaireVersionId=0'qV.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
                logItem.QuestionnaireAnswerId=0'questionnaireAnswer.Id(value is being set to zero(0),just to redirect the user to the staff and access page)
                logItem.Type ="Staff & Access"
                logItem.Category ="Staff & Access"
                logItem.QuestionName = "Staff role"
                logItem.Answer =""
                logItem.Description ="Each staff person must be assigned with a role." 'qI.ValidationMessage(There exists no validationMessage for this qI,so the Description is hardCoded)
                logItem.Completed =False
                SaveLogItem(logItem)				
                exit for
            End If				
        Next	

        intrinsicProtocol.Save(intrinsicConnection)
    End Sub

    'Save LogItem
    Sub SaveLogItem(ByVal logItem As Humans.LogItem)
        intrinsicProtocolProcess.SaveLogItem(logItem)
    End Sub

    private function LogMissingItem(byval questionnaireVersionId as integer, byval questionnaireAnswerId as integer, byval logType as string, byval category as string, byval questionName as string, byval answer as string, byval description as string)
        Dim logItem As New Humans.LogItem(intrinsicCachePolicy)
        logItem.QuestionnaireVersionId = questionnaireVersionId
        logItem.QuestionnaireAnswerId = questionnaireAnswerId
        logItem.Type = logType
        logItem.QuestionName = questionName
        logItem.Category = category
        logItem.Answer = answer
        logItem.Description = description
        logItem.Completed =False
        SaveLogItem(logItem)
    end function
					
end module